package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS83002Srvl
 */
public class CS83002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnUserId;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS83002Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings({ "unchecked", "unused" })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	
    	// get site_id
    	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("process_type");
		if (vaProcessType.equals("getDataTable")){
			getDataTable(request, response);
		} else if (vaProcessType.equals("deleteData")) {
			deleteData(request, response);
		} else {
			//editData(request, response);
		}
	}
    
    @SuppressWarnings({ "unchecked", "unused" })
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	this.db = new Database();
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();	
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		String vaUserId = "";
		String vaUserFName = "";
		if (request.getParameter("sSearch_0").equals("")) {
			vaUserId = "";
		} else {
			vaUserId = request.getParameter("sSearch_0").trim();
		}
		if (request.getParameter("sSearch_1").equals("")) {
			vaUserFName = "";
		} else {
			vaUserFName = request.getParameter("sSearch_1").trim();
		}
		String[] vaColumnsASC = { "user_id ASC", "user_id ASC", "user_fname ASC",
				"user_position ASC", "telephone ASC" };
		String[] vaColumnsDESC = { "user_id DESC", "user_id DESC", "user_fname DESC",
				"user_position DESC", "telephone DESC" };

		String vaSortColumn = null;
		int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
		String vaSortDirection = request.getParameter("sSortDir_0");
		
		if (vaSortDirection.equals("asc")) {
			vaSortColumn = vaColumnsASC[vnSortColumn];
		}
		if (vaSortDirection.equals("desc")) {
			vaSortColumn = vaColumnsDESC[vnSortColumn];
		}
		UserLoginDAO voUserLoginDAO = new UserLoginDAO(db);
		List<Map<String , Object>> voListFindAll = null;
		Map<String , Object> voMapItem = null;
		int vnEnd = vnStart + vnAmount;
		int vnTotalRecords = voUserLoginDAO.getCountAllUserLoginByUserId(vaUserId, vaUserFName);
		int vnTotalDisplayRecords = 0;
		if (vnAmount == -1) {
			voListFindAll = voUserLoginDAO.findAllUserLoginByUserId(vaUserId, vaUserFName, vaSortColumn);
			vnTotalDisplayRecords = vnTotalRecords;
		} else {
			voListFindAll = voUserLoginDAO.findUserLoginByUserId(vaUserId, vaUserFName, vaSortColumn, vnStart, vnEnd);
			vnTotalDisplayRecords = voUserLoginDAO.getCountAllUserLoginByUserId(vaUserId, vaUserFName);
		}
		for(int i = 0; i < voListFindAll.size() ; i++){
			voMapItem = voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			voColumn.add(voMapItem.get("USER_ID"));
			voColumn.add(voMapItem.get("USER_FULLNAME"));
			voColumn.add(voMapItem.get("USER_POSITION"));
			voColumn.add(voMapItem.get("TELEPHONE"));
			voColumn.add(voMapItem.get("STATUS"));
			voRow.add(voColumn);
		}
		
		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		db.close();
		voOut.print(voObject.toJSONString());
    }
    
    public void deleteData(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaUserId = request.getParameter("userId");

		UserLoginDAO voUserLoginDAO = new UserLoginDAO(db);
		boolean vbResultData = false;
		try {
			db.beginTransaction();
			vbResultData = voUserLoginDAO.deleteUser(vaUserId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS83002", JDate.getDate(), JDate.getTime(),vnUserId, "CS83002Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		//db.close();
		
		if (vbResultData)
			response.getWriter().write("delete_sucess");
		else
			response.getWriter().write("delete_fail");
	}
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
